﻿namespace SharePointRing.Framework.Helpers
{
    using Microsoft.SharePoint.Administration;
    using Microsoft.Web.Administration;
    using SharePointRing.Framework.Model;
    using System.Collections.Generic;
    using System.Security;
    
    public static class SPFarmHelper
    {
        public static string GetBaseIisPath()
        {
            var centralAdminWebApplication = SPAdministrationWebApplication.Local;

            var centralAdminIisPhysicalPath = centralAdminWebApplication.IisSettings[SPUrlZone.Default].Path.ToString();
            var baseIisPath = centralAdminIisPhysicalPath.Substring(0, centralAdminIisPhysicalPath.LastIndexOf("\\") + 1);

            return baseIisPath;
        }

        public static string GetDefaultContentDatabaseServer()
        {
            SPWebApplicationBuilder webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);
            return webAppBuilder.DatabaseServer;
        }

        public static List<ManagedAccountInfo> GetAllManagedAccounts()
        {
            var result = new List<ManagedAccountInfo>();

            SPFarmManagedAccountCollection collection = new SPFarmManagedAccountCollection(SPFarm.Local);
            foreach (SPManagedAccount account in collection)
            {
                result.Add(new ManagedAccountInfo() { Username = account.Username });
            }

            return result;
        }

        public static List<ApplicationPoolInfo> GetAllApplicationPools()
        {
            var result = new List<ApplicationPoolInfo>();

            SPFarm farm = SPFarm.Local;
            SPWebService service = farm.Services.GetValue<SPWebService>(string.Empty);

            foreach (SPApplicationPool appPool in service.ApplicationPools)
            {
                result.Add(new ApplicationPoolInfo() { Id = appPool.Id, Name = appPool.Name, Username = appPool.Username });
            }

            return result;
        }

        public static SecureString ConvertStringToSecureString(string unsecureString)
        {
            SecureString secureString = new SecureString();

            char[] unsecureChars = unsecureString.ToCharArray();
            foreach (char unsecureChar in unsecureChars)
            {
                secureString.AppendChar(unsecureChar);
            }

            return secureString;
        }
    }
}
